<?php

namespace App\Controllers;

use App\Models\UserActivityLogModel;
use App\Models\StudyLocationModel;

class UserActivityLog extends BaseController
{
	public function index()
    {
        $userActivityLogModel = new UserActivityLogModel();
        $studyLocationModel = new StudyLocationModel();

         // 使用 select() 方法的第二个参数 false 禁用自动转义
        $userActivityLogModel->select('user_activity_logs.*, study_location.name as location_name, study_location.location_order as location_order', false);
        $userActivityLogModel->select("CASE 
                         WHEN user_activity_logs.action_type = 'click' THEN '用户点击'
                         ELSE user_activity_logs.action_type
                     END as action_type_text", false);
        
        $clickActivities = $userActivityLogModel
            ->join('study_location', 'user_activity_logs.page_id = study_location.id', 'left')
            ->where('action_type', 'click')
            ->findAll();

        // 重置模型以进行下一个查询
        $userActivityLogModel->resetQuery();
        
        // 同样为停留活动添加 action_type_text 字段
        $userActivityLogModel->select('user_activity_logs.*, study_location.name as location_name, study_location.location_order as location_order', false);
        $userActivityLogModel->select("CASE 
                         WHEN user_activity_logs.action_type = 'stay' THEN '页面停留'
                         ELSE user_activity_logs.action_type
                     END as action_type_text", false);
        
        $stayActivities = $userActivityLogModel
            ->join('study_location', 'user_activity_logs.page_id = study_location.id', 'left')
            ->where('action_type', 'stay')
            ->findAll();

        return view('activity_log_index', [
            'clickActivities' => $clickActivities,
            'stayActivities' => $stayActivities
        ]);
    }

    public function recordClickActivity()
    {
    	$actionType = "click";
    	$duration = "";
        // 获取用户的 IP 地址
        // $ipAddress = $this->request->getIPAddress();
         $ipAddress = $this->getClientIpAddress();

        $request = service('request');
        $jsonData = $request->getJSON();

        if ($jsonData) {
            // 从对象中获取 page_id 参数
            $pageId = $jsonData->page_id;

            // 获取当前时间
	        $actionTime = date('Y-m-d H:i:s');

	        // 实例化 UserActivityLogModel
	        $userActivityLogModel = new UserActivityLogModel();

	        // 准备要插入的数据
	        $data = [
	            'ip_address' => $ipAddress,
	            'page_id' => $pageId,
	            'action_type' => "click",
	            'action_time' => $actionTime,
	            'duration' => $duration
	        ];

	        // 插入数据到数据库
	        if ($userActivityLogModel->insert($data)) {
	            log_message('info', "Activity recorded successfully. IP: $ipAddress, URL: $pageId, Action: $actionType, Duration: $duration");
	            return $this->response->setJSON(['status' => 'success', 'message' => '点击活动记录成功', 'page_id' => $pageId]);
	        } else {
	            log_message('error', "Failed to record activity. IP: $ipAddress, URL: $pageId, Action: $actionType, Duration: $duration");
	            return $this->response->setJSON(['status' => 'error', 'message' => '活动记录失败']);
	        }
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => '未接收到有效的 JSON 数据'
            ]);
        }
    }

    public function recordStayActivity()
    {
    	$actionType = "stay";

        // 获取用户的 IP 地址
        // $ipAddress = $this->request->getIPAddress();
         $ipAddress = $this->getClientIpAddress();

        $request = service('request');
        $jsonData = $request->getJSON();
	    log_message('info', "Activity recorded successfully. IP: $jsonData->duration");
        
        if ($jsonData) {
            // 从对象中获取 page_id 参数
            $pageId = $jsonData->pageId;
            $duration = $jsonData->duration;
			
			// 获取当前时间
	        $actionTime = date('Y-m-d H:i:s');

	        // 实例化 UserActivityLogModel
	        $userActivityLogModel = new UserActivityLogModel();

	        // 准备要插入的数据
	        $data = [
	            'ip_address' => $ipAddress,
	            'page_id' => $pageId,
	            'action_type' => "stay",
	            'action_time' => $actionTime,
	            'duration' => $duration
	        ];
            
            // 插入数据到数据库
	        if ($userActivityLogModel->insert($data)) {
	            return $this->response->setJSON(['status' => 'success', 'message' => '停留活动记录成功', 'page_id' => $pageId, 'Duration' => $duration]);
	        } else {
	            return $this->response->setJSON(['status' => 'error', 'message' => '停留活动记录失败', 'page_id' => $pageId, 'Duration' => $duration]);
	        }
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => '未接收到有效的 JSON 数据'
            ]);
        }
    }

    private function getClientIpAddress()
    {
        // 尝试从各种 HTTP 头信息获取可能的客户端 IP
        $ip = $this->request->getIPAddress();
        
        // 检查是否有代理服务器
        if ($this->request->hasHeader('X-Forwarded-For')) {
            $ip = $this->request->getHeaderLine('X-Forwarded-For');
            // X-Forwarded-For 可能包含多个 IP（客户端,代理1,代理2...）
            $ips = explode(',', $ip);
            $ip = trim($ips[0]);
        }
        
        return $ip;
    }

    public function exportClickCsv()
    {
        $userActivityLogModel = new UserActivityLogModel();
        $studyLocationModel = new StudyLocationModel();

        $userActivityLogModel->select('user_activity_logs.*, study_location.name as location_name, study_location.location_order as location_order', false);
        $userActivityLogModel->select("CASE 
                         WHEN user_activity_logs.action_type = 'click' THEN '用户点击'
                         ELSE user_activity_logs.action_type
                     END as action_type_text", false);
        
        $clickActivities = $userActivityLogModel
            ->join('study_location', 'user_activity_logs.page_id = study_location.id', 'left')
            ->where('action_type', 'click')
            ->findAll();

        // 设置 CSV 文件的表头
        $headers = [
            '序号',
            '活动类型',
            '用户网络地址',
            '用户点击的研学地编号',
            '用户点击的研学地名称',
            '活动时间'
        ];

        // 设置响应头
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="用户链接点击事件数据记录表.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');

        // 打开 PHP 输出流
        $output = fopen('php://output', 'w');

        // 写入 BOM 头以避免中文乱码
        fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));

        // 写入表头
        fputcsv($output, $headers);

        // 写入数据
        $index = 1;
        foreach ($clickActivities as $activity) {
            $row = [
                $index++,
                $activity['action_type_text'] ?? '',
                $activity['ip_address'] ?? '',
                $activity['location_order'] ?? '',
                $activity['location_name'] ?? '',
                $activity['action_time'] ?? '',
            ];
            fputcsv($output, $row);
        }

        // 关闭输出流
        fclose($output);
    }

    public function exportStayCsv()
    {
        $userActivityLogModel = new UserActivityLogModel();
        $studyLocationModel = new StudyLocationModel();

        $userActivityLogModel->select('user_activity_logs.*, study_location.name as location_name, study_location.location_order as location_order', false);
        $userActivityLogModel->select("CASE 
                         WHEN user_activity_logs.action_type = 'stay' THEN '页面停留'
                         ELSE user_activity_logs.action_type
                     END as action_type_text", false);
        
        $stayActivities = $userActivityLogModel
            ->join('study_location', 'user_activity_logs.page_id = study_location.id', 'left')
            ->where('action_type', 'stay')
            ->findAll();

        // 设置 CSV 文件的表头
        $headers = [
            '序号',
            '活动类型',
            '用户网络地址',
            '用户停留的研学地编号',
            '用户停留的研学地名称',
            '停留时间(秒)',
            '活动时间'
        ];

        // 设置响应头
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="用户页面停留事件数据记录表.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');

        // 打开 PHP 输出流
        $output = fopen('php://output', 'w');

        // 写入 BOM 头以避免中文乱码
        fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));

        // 写入表头
        fputcsv($output, $headers);

        // 写入数据
        $index = 1;
        foreach ($stayActivities as $activity) {
            $row = [
                $index++,
                $activity['action_type_text'] ?? '',
                $activity['ip_address'] ?? '',
                $activity['location_order'] ?? '',
                $activity['location_name'] ?? '',
                $activity['duration'] ?? '',
                $activity['action_time'] ?? '',
            ];
            fputcsv($output, $row);
        }

        // 关闭输出流
        fclose($output);
    }
}